package main

import (
	"fmt"
	"path"

	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()
	r.POST("/upload", UploadOne)
	r.POST("/uploads", UploadMany)
	r.Run()
}

// todo 修改上传图片存储路径
var commonPath = "/Users/lena/GoWork/golang/golang-learning-code/web/gin/upload/picture"

func UploadOne(c *gin.Context) {
	// 通过<input>的name属性获取图片
	file, err := c.FormFile("picture")
	if err != nil {
		fmt.Println("get picture:", err)
		return
	}
	dst := path.Join(commonPath, file.Filename)
	err = c.SaveUploadedFile(file, dst)
	if err != nil {
		fmt.Println("upload error:", err)
		return
	}
	fmt.Println("upload success!")
}

func UploadMany(c *gin.Context) {
	form, err := c.MultipartForm()
	if err != nil {
		fmt.Println("get picture:", err)
		return
	}
	files := form.File["pictures"]
	for _, file := range files {
		fmt.Println("文件名:", file.Filename)
		dst := path.Join(commonPath, file.Filename)
		c.SaveUploadedFile(file, dst)
	}
	fmt.Println("upload success!")
}
